<?php

namespace App\Service\Invoice\Web;

use App\Library\FeiShu\SendFs;
use App\Library\Rms\RmsShopApi;
use App\Library\Rms\RmsUserApi;
use App\Models\Invoice\InvoiceHistoryModel;
use App\Service\BaseService;
use App\Service\Common\CommonService;
use App\Service\OpenShop\User\RmsUserService;
use App\Exports\Invoice\InvoiceExport;
use GuzzleHttp\Exception\GuzzleException;
use Kuafu\GeneralFs\BuildFs;

class InvoiceService extends BaseService
{

    /**
     * 查看开票记录列表
     * @param array $data
     * @param int $pageSize
     * @param int $pageNum
     * @param int $export
     * @return array
     */
    public static function lists(array $data, int $pageSize, int $pageNum, int $export): array
    {
        $paginator = InvoiceHistoryModel::query()
            ->where('status', '>', 0)
            ->with(['businessRel'])
            ->when(
                $data['shopIds'], function ($query) use ($data) {
                $query->whereIn('invoice_history.shopId', explode(',', $data['shopIds']));//门店id
            }
            )
            ->when(
                $data['blueInvoiceNumber'], function ($query) use ($data) {
                $query->where('invoice_history.blueInvoiceNumber', $data['blueInvoiceNumber']);//发票号码
            }
            )
            ->when(
                $data['orderNum'], function ($query) use ($data) {
                $query->join('invoice_history_business_rel', 'invoice_history_business_rel.invoiceHistoryId', 'invoice_history.id')
                    ->where('invoice_history_business_rel.businessId', $data['orderNum']);//订货单号
            }
            )
            ->when(
                $data['invoiceType'] != '', function ($query) use ($data) {
                $query->whereIn('invoice_history.invoiceType', explode(',', $data['invoiceType']));//发票类型
            }
            )
            ->when(
                $data['status'] != '', function ($query) use ($data) {
                $query->whereIn('invoice_history.status', explode(',', $data['status']));//发票状态
            }
            )
            ->when(
                $data['channel'] != '', function ($query) use ($data) {
                $query->whereIn('invoice_history.channel', explode(',', $data['channel']));//开票渠道
            }
            )
            ->when(
                $data['headerType'] != '', function ($query) use ($data) {
                $query->whereIn('invoice_history.headerType', explode(',', $data['headerType']));//抬头类型
            }
            )
            ->when(
                $data['invoiceTitle'], function ($query) use ($data) {
                $query->where('invoice_history.invoiceTitle', 'like', "%{$data['invoiceTitle']}%");//发票抬头
            }
            )
            ->when(
                $data['name'], function ($query) use ($data) {
                $createdByUids = collect((new RmsUserApi())->getInfoByUsernames([$data['name']])['data'])->pluck('id')->toArray();
                if ($createdByUids) {
                    $query->whereIn('invoice_history.createdByUid', $createdByUids);//申请人名字
                }
            }
            )
            ->when(
                $data['startTime'] && $data['endTime'], function ($query) use ($data) {
                $query->whereBetween('invoice_history.blueInvoiceTime', [$data['startTime'], $data['endTime']]);//开票日期
            }
            )
            ->orderByDesc('invoice_history.createdAt')
            ->paginate($pageSize, ['invoice_history.*'], 'pageNum', $pageNum);

        $shopIds       = collect($paginator->items())->pluck('shopId')->toArray();
        $createdByUids = collect($paginator->items())->pluck('createdByUid')->toArray();
        //门店信息
        $shopList  = collect((new RmsShopApi())->getShopByIds($shopIds, ['id', 'shopCode', 'name', 'addressPrefix'])['data']['shopList'] ?? [])->keyBy('id');
        $userInfos = collect(RmsUserService::getRmsUserInfoByUserIds($createdByUids)['data'] ?? [])->keyBy('id');

        $lists = $paginator->map(
            function (InvoiceHistoryModel $invoiceHistoryModel) use ($userInfos, $shopList) {
                $invoiceFile = $invoiceHistoryModel->blueInvoiceOssFile;//蓝字发票文件地址
                if ($invoiceHistoryModel->status == InvoiceHistoryModel::STATUS_5) {   //发票红冲成功
                    $invoiceFile = $invoiceHistoryModel->redInvoiceOssFile;            //红字发票文件地址
                }
                $blueTaxValueTotal = $invoiceHistoryModel->blueTaxValueTotal;
                if (!$blueTaxValueTotal) {
                    $blueTaxValueTotal = round($invoiceHistoryModel->invoiceTotalAmount + $invoiceHistoryModel->invoiceTaxTotalAmount, 2);
                }
                return [
                    'id'                 => $invoiceHistoryModel->id,
                    'shopId'             => $invoiceHistoryModel->shopId,                                    //门店id
                    'shopCode'           => $shopList[$invoiceHistoryModel->shopId]['shopCode'] ?? '-',      //门店编号
                    'shopName'           => $shopList[$invoiceHistoryModel->shopId]['name'] ?? '-',          //门店名称
                    'addressPrefix'      => $shopList[$invoiceHistoryModel->shopId]['addressPrefix'] ?? '-', //省市区
                    'blueInvoiceTime'    => formatDateYmd($invoiceHistoryModel->blueInvoiceTime),            //开票时间
                    'createdAt'          => $invoiceHistoryModel->createdAt->toDateTimeString(),             //记录创建时间
                    'blueInvoiceNumber'  => $invoiceHistoryModel->blueInvoiceNumber,                         //发票号码
                    'status'             => $invoiceHistoryModel->status,                                    //开票状态
                    'statusText'         => InvoiceHistoryModel::STATUS_TEXT[$invoiceHistoryModel->status] ?? "",
                    'invoiceType'        => $invoiceHistoryModel->invoiceType,//发票类型
                    'invoiceTypeText'    => InvoiceHistoryModel::INVOICE_TYPE_TEXT[$invoiceHistoryModel->invoiceType] ?? "",
                    'channel'            => $invoiceHistoryModel->channel,//开票渠道
                    'channelText'        => InvoiceHistoryModel::CHANNEL_TYPE_TEXT[$invoiceHistoryModel->channel] ?? "",
                    'headerType'         => $invoiceHistoryModel->headerType,//抬头类型
                    'headerTypeText'     => InvoiceHistoryModel::HEADER_TYPE_TEXT[$invoiceHistoryModel->headerType] ?? "",
                    'invoiceTitle'       => $invoiceHistoryModel->invoiceTitle,                                 //发票抬头
                    'companyTaxNumber'   => $invoiceHistoryModel->companyTaxNumber,                             //公司税号
                    'invoiceFile'        => $invoiceFile,                                                       //发票文件地址
                    'invoiceTotalAmount' => $invoiceHistoryModel->invoiceTotalAmount,                           //订单金额
                    'blueTaxValueTotal'  => $blueTaxValueTotal,                                                 //价税合计 包括税额
                    'applyName'          => $userInfos[$invoiceHistoryModel->createdByUid]['username'] ?? '-',  //申请人
                    'operatorName'       => '系统',                                                               //操作人
                    'businessInfo'       => collect($invoiceHistoryModel->businessRel)->map(
                        function ($item) {
                            return [
                                'id'                 => $item->id,
                                'totalInvoiceAmount' => $item->invoiceTotalAmount,             //实付金额
                                'businessId'         => $item->businessId,                     //订货单号
                                'createdAt'          => formatDate($item->businessOrderTime),  //下单时间
                            ];
                        }
                    )->toArray(),
                ];
            }
        );
        if ($export) {
            return excelDownload(new InvoiceExport(Collect($lists)), '发票记录列表-' . date('Y-m-d') . "-" . time());
        }

        return [
            'pageNum'   => $paginator->currentPage(),
            'pageSize'  => $paginator->perPage(),
            'pageCount' => ceil($paginator->total() / $paginator->perPage()),
            'count'     => $paginator->total(),
            'lists'     => $lists,
            'search'    => [//搜索
                "invoiceTypeText" => enumToSelection(InvoiceHistoryModel::INVOICE_TYPE_TEXT),
                "statusText"      => enumToSelection(InvoiceHistoryModel::STATUS_TEXT),
                "channelText"     => enumToSelection(InvoiceHistoryModel::CHANNEL_TYPE_TEXT),
                "headerTypeText"  => enumToSelection(InvoiceHistoryModel::HEADER_TYPE_TEXT),
            ],
        ];
    }

    /**
     * 查看开票记录详情
     * @param int $id
     * @return array
     * @throws GuzzleException
     */
    public static function info(int $id): array
    {
        $invoiceHistoryModel = InvoiceHistoryModel::query()->where('id', $id)->first();
        if (!$invoiceHistoryModel) {
            return [];
        }
        $userIds[] = $invoiceHistoryModel->createdByUid ?? 0;
        $userIds[] = $invoiceHistoryModel->updatedByUid ?? 0;
        //门店信息
        $shopList  = collect((new RmsShopApi())->getShopByIds([$invoiceHistoryModel->shopId], ['id', 'shopCode', 'name', 'addressPrefix'])['data']['shopList'] ?? [])->keyBy('id');
        $userInfos = collect(RmsUserService::getRmsUserInfoByUserIds(array_unique($userIds))['data'] ?? [])->keyBy('id');

        $invoiceFile = $invoiceHistoryModel->blueInvoiceOssFile;   //蓝字发票文件地址
        $updatedName = $updatedAt = '';
        if ($invoiceHistoryModel->status == InvoiceHistoryModel::STATUS_5) {  //发票红冲成功
            $invoiceFile = $invoiceHistoryModel->redInvoiceOssFile;           //红字发票文件地址
            $updatedName = $userInfos[$invoiceHistoryModel->updatedByUid]['username'] ?? '-';
            $updatedAt   = $invoiceHistoryModel->updatedAt->toDateTimeString();
        }

        return array_merge(
            $invoiceHistoryModel->toArray(),
            [
                'shopCode'              => $shopCode = $shopList[$invoiceHistoryModel->shopId]['shopCode'] ?? '-',//门店编号
                'shopName'              => $shopName = $shopList[$invoiceHistoryModel->shopId]['name'] ?? '-',    //门店名称
                'addressPrefix'         => $shopList[$invoiceHistoryModel->shopId]['addressPrefix'] ?? '-',       //省市区
                'blueInvoiceTime'       => formatDateYmd($invoiceHistoryModel->blueInvoiceTime),                  //开票时间
                'createdAt'             => $invoiceHistoryModel->createdAt->toDateTimeString(),                   //记录创建时间
                'updatedAt'             => $updatedAt,                                                           //修改时间
                'statusText'            => InvoiceHistoryModel::STATUS_TEXT[$invoiceHistoryModel->status] ?? "",
                'invoiceTypeText'       => InvoiceHistoryModel::INVOICE_TYPE_TEXT[$invoiceHistoryModel->invoiceType] ?? "",
                'channelText'           => InvoiceHistoryModel::CHANNEL_TYPE_TEXT[$invoiceHistoryModel->channel] ?? "",
                'headerTypeText'        => InvoiceHistoryModel::HEADER_TYPE_TEXT[$invoiceHistoryModel->headerType] ?? "",
                'invoiceFile'           => $invoiceFile,                                                         //发票文件地址
                'invoiceTotalAmount'    => $invoiceHistoryModel->invoiceTotalAmount,                             //开票金额
                'invoiceTaxTotalAmount' => $invoiceHistoryModel->invoiceTaxTotalAmount,                          //开票总税额
                'blueTaxValueTotal'     => $invoiceHistoryModel->blueTaxValueTotal,                              //价税合计 包括税额
                'applyName'             => $userInfos[$invoiceHistoryModel->createdByUid]['username'] ?? '-',    //申请人
                'updatedName'           => $updatedName,                                                         //修改人
                'operatorName'          => '系统',                                                                 //操作人
                'businessDetails'       => json_decode($invoiceHistoryModel->businessDetails ?? "", true) ?? [], //开票业务明细
                'remark'                => $invoiceHistoryModel->remark,                                         //备注
            ]
        );
    }

    /**
     * 订货发票相关推送通知消息
     * @param int $id
     * @param int $status
     * @throws GuzzleException
     */
    public static function sendFs(int $id, int $status)
    {
        $invoiceHistoryModel = InvoiceHistoryModel::query()->with(['businessRel'])->where('id', $id)->first();
        if (!$invoiceHistoryModel) {
            return;
        }
        //门店信息
        $shopList  = collect((new RmsShopApi())->getShopByIds([$invoiceHistoryModel->shopId], ['id', 'shopCode', 'name', 'addressPrefix'])['data']['shopList'] ?? [])->keyBy('id');
        $userInfos = collect(RmsUserService::getRmsUserInfoByUserIds([$invoiceHistoryModel->createdByUid])['data'] ?? [])->keyBy('id');

        $username        = CommonService::getUserInfoHide($userInfos[$invoiceHistoryModel->createdByUid]['username'] ?? '-', 'name', true);
        $userMobile      = CommonService::getUserInfoHide($userInfos[$invoiceHistoryModel->createdByUid]['mobile'] ?? '-', 'mobile', true);
        $headerTypeText  = InvoiceHistoryModel::HEADER_TYPE_TEXT[$invoiceHistoryModel->headerType] ?? "";  //抬头类型
        $invoiceTypeText = InvoiceHistoryModel::INVOICE_TYPE_TEXT[$invoiceHistoryModel->invoiceType] ?? "";//发票类型

        $orderData = [];
        collect($invoiceHistoryModel->businessRel)->map(
            function ($item) use (&$orderData) {
                $orderData[] = $item->businessId; //订货单号
            }
        );

        $invoiceTitle = $invoiceHistoryModel->invoiceTitle;
        if ($invoiceHistoryModel->headerType == InvoiceHistoryModel::HEADER_TYPE_1) {//企业税号
            $invoiceTitle .= '\n企业税号：' . $invoiceHistoryModel->companyTaxNumber;
        }
        $blueInvoiceNumber = $invoiceHistoryModel->blueInvoiceNumber;//发票号码
        if ($blueInvoiceNumber) {
            $invoiceTitle .= '\n发票号码：' . $blueInvoiceNumber;
        }
        $blueInvoiceTime = formatDateYmd($invoiceHistoryModel->blueInvoiceTime); //开票时间
        if ($blueInvoiceTime) {
            $invoiceTitle .= '\n开票日期：' . $blueInvoiceTime;
        }
        $invoiceFile = $invoiceHistoryModel->blueInvoiceOssFile;//蓝字发票文件地址
        if ($invoiceHistoryModel->status == InvoiceHistoryModel::STATUS_5) {   //发票红冲成功
            $invoiceFile = $invoiceHistoryModel->redInvoiceOssFile;            //红字发票文件地址
        }
        if ($invoiceFile) {
            $invoiceTitle .= '\n发票链接：[查看发票](' . $invoiceFile . ')';
        }

        $jumpUrl = \App\Service\OpenShop\Feishu\BaseService::getInvoiceListUrl($id);

        $title     = InvoiceHistoryModel::FS_NOTICE_STATUS_TEXT[$status] ?? '开票成功';
        $statusDes = InvoiceHistoryModel::FS_NOTICE_STATUS_DESC_TEXT[$status] ?? '开票成功';
        $color     = InvoiceHistoryModel::FS_NOTICE_STATUS_COLOR[$status] ?? 'blue';

        $templateData = [
            'shopCode'          => $shopCode = $shopList[$invoiceHistoryModel->shopId]['shopCode'] ?? '-',    //门店编号
            'shopName'          => $shopCode . ($shopList[$invoiceHistoryModel->shopId]['name'] ?? '-'),      //门店名称
            'applyTime'         => $invoiceHistoryModel->createdAt->toDateTimeString(),                       //申请时间
            'applyName'         => $username . '（' . $userMobile . '）',                                       //申请人
            'blueTaxValueTotal' => $invoiceHistoryModel->blueTaxValueTotal,                                   //开票金额
            'typeText'          => $headerTypeText . '（' . $invoiceTypeText . '）',                            //开票类型
            'invoiceTitle'      => $invoiceTitle,                                                             //开票抬头
            'blueInvoiceNumber' => $invoiceHistoryModel->blueInvoiceNumber,                                   //发票号码
            'blueInvoiceTime'   => formatDateYmd($invoiceHistoryModel->blueInvoiceTime),                      //开票时间
            'invoiceOssFile'    => $invoiceFile,                                                              //发票链接
            'totalOrder'        => count($orderData),                                                         //业务订单 数量
            'orderInfo'         => implode('\n', $orderData),                                                 //订单号
            'jumpUrl'           => $jumpUrl,                                                                  //跳转链接
            'color'             => $color,                                                                    //标题颜色
            'title'             => '【' . $title . '】 ' . $shopCode . ' ' . $statusDes,                        //标题
        ];

        $templateJson = view()->file(app_path("Remote/Feishu/FsTemplate/Invoice/InvoiceFsTemplate.blade.php"), $templateData)->render();

        BuildFs::newRobot(SendFs::ROBOT_INVOICE, BuildFs::MSG_TYPE_CARD)
            ->setCardContent(json_decode($templateJson, true))
            ->send();
    }
}
